/*
 * nodejs-web 程序入口
 */

var wechat = require('wechat');
var config = require('config');
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var mongodb = require('./mongodb');
var storage = require('./storage');
var wxapi = require('./wxapi');
var log = require('./log');

var app = express();
log.use(app);

app.use(express.query());
app.use(cookieParser());
app.use(session(config.get('session')));

app.get('/', function(req, res) {
    res.send("微信公众号测试平台: wx.ilulin.com<br/>" +
    ">>>部署自己的微信公众号后台，<a href='https://bce.baidu.com/product/bae.html'" +
    "target='_blank'>请前往BAE</a><br/>" +
    ">>>查看基于nodejs的微信公众号后台实现代码，" +
    "<a href='http://git.oschina.net/killu/nodewechat'" +
    "target='_blank'>请前往OSC代码仓库</a><br/>" +
    ">>>查看实现效果，请关注微信公众号: ilulin-com 进行操作<br/>" +
    "<img src='http://ilulin.bj.bcebos.com/wechat/qrcode_for_gh_6f1283234e02_344.jpg'/><br/>" +
    ">>>                                  " +
    "by <a href='http://ilulin.com' target='_blank'>ilulin.com</a><br/>");
});

// 普通订阅号不支持创建自定义菜单
app.get('/api/menu/create', function(req, res) {
    wxapi.createMenu(function (err, result) {
        res.send('微信公众号(ilulin-com) 创建菜单结果: ' + JSON.stringify(result));
    });
});

// 抓取永久素材并保存
app.get('/api/materials', function(req, res) {
    wxapi.getMaterials(function (err, result) {
        if (err) {
            res.send('微信公众号(ilulin-com) 抓取永久是在结果: ' + JSON.stringify(err));
        } else {
            storage.putMaterial(result);
        }
    });
});

var handle = function(mode, message, req, res) {
    if (req.wxsession.mode === 'debug') {
        if (message.Content === 'e') {
            req.wxsession.mode = '';
            res.reply('已经退出调试模式');
        } else {
            res.reply(JSON.stringify(message) + "\n（回复e退出）");
        }
    } else if (req.wxsession.mode === 'chat') {
        if (message.Content === 'e') {
            req.wxsession.mode = '';
            res.reply('已经退出聊天模式');
        } else {
            res.reply('还没对接聊天机器人，呵呵呵\n（回复e退出）');
        }
    } else {
        req.wxsession.mode = mode;
        if (mode === 'chat') {
            res.reply('已经进入聊天模式\n（回复e退出）');
        } else if (mode === 'debug') {
            res.reply('已经进入调试模式\n（回复e退出）');
        } else {
            res.wait('view');
        }
    }
};

var handle2 = function(type, message, req, res) {
    if (req.wxsession.mode === 'debug') {
        res.reply(JSON.stringify(message));
    } else if (req.wxsession.mode == 'chat') {
        res.reply('聊天模式不收' + type + '\n（回复e退出）')
    } else {
        res.reply(type + "不收，哈哈哈");
    }
};

var List = require('wechat').List;
List.add('view', [
    ['回复{a}查看最新文章', function (message, req, res) {
        storage.putMessage(message);
        storage.getLatestPost(function (err, items) {
            if (err) {
                console.log(err);
                res.reply(JSON.stringify(err));
            } else {
                res.reply(items);
            }
        });
    }],
    ['回复{c}进入聊天模式', function (message, req, res) {
        storage.putMessage(message);
        handle('chat', message, req, res);
    }],
    ['回复{d}进入调试模式', function (message, req, res) {
        storage.putMessage(message);
        handle('debug', message, req, res);
    }],
    ['回复{o}查看后台源码', function (message, req, res) {
        storage.putMessage(message);
        res.reply([{
            title: 'nodewechat',
            description: 'nodewechat微信后台学习的好项目',
            picurl: 'http://ilulin.bj.bcebos.com/wechat/wechat.png',
            url: 'http://git.oschina.net/killu/nodewechat'
        }]);
    }],
    ['回复{k}看是谁在折腾', function (message, req, res) {
        storage.putMessage(message);
        res.reply([{
                title: '苦逼程序员',
                description: '一个苦逼程序员的网站: ilulin.com',
                picurl: 'http://ilulin.bj.bcebos.com/wechat/danfeng-1.jpg',
                url: 'http://ilulin.com/index.php/danfeng/'
            }]
        );
    }]
]);

app.use('/wechat', wechat(config.get('wx'), wechat.text(function (message, req, res, next) {
    storage.putMessage(message);
    handle('', message, req, res);
    // message为文本内容
    // { ToUserName: 'gh_d3e07d51b513',
    // FromUserName: 'oPKu7jgOibOA-De4u8J2RuNKpZRw',
    // CreateTime: '1359125035',
    // MsgType: 'text',
    // Content: 'http',
    // MsgId: '5837397576500011341' }
}).image(function(message, req, res, next) {
    storage.putMessage(message);
    var object = 'wechat/' + message.FromUserName + '/image/' + message.MsgId;
    storage.putImage(message.PicUrl, object, function (err, url) {
        if (req.wxsession.mode === 'debug') {
            res.reply(JSON.stringify(message));
        } else if (req.wxsession.mode == 'chat') {
            res.reply('聊天模式不收image\n（回复e退出）')
        } else {
            if (err) {
                res.reply(JSON.stringify(err));
            } else {
                res.reply("image收下\n" + url);
            }
        }
    });
    // message为图片内容
    // { ToUserName: 'gh_d3e07d51b513',
    // FromUserName: 'oPKu7jgOibOA-De4u8J2RuNKpZRw',
    // CreateTime: '1359124971',
    // MsgType: 'image',
    // PicUrl: 'http://mmsns.qpic.cn/mmsns/bfc815ygvIWcaaZlEXJV7NzhmA3Y2fc4eBOxLjpPI60Q1Q6ibYicwg/0',
    // MediaId: 'media_id',
    // MsgId: '5837397301622104395' }
}).voice(function(message, req, res, next){
    storage.putMessage(message);
    handle2('voice', message, req, res);
    // message为音频内容
    // { ToUserName: 'gh_d3e07d51b513',
    // FromUserName: 'oPKu7jgOibOA-De4u8J2RuNKpZRw',
    // CreateTime: '1359125022',
    // MsgType: 'voice',
    // MediaId: 'OMYnpghh8fRfzHL8obuboDN9rmLig4s0xdpoNT6a5BoFZWufbE6srbCKc_bxduzS',
    // Format: 'amr',
    // MsgId: '5837397520665436492' }
}).video(function(message, req, res, next){
    storage.putMessage(message);
    handle2('video', message, req, res);
    // message为视频内容
    // { ToUserName: 'gh_d3e07d51b513',
    // FromUserName: 'oPKu7jgOibOA-De4u8J2RuNKpZRw',
    // CreateTime: '1359125022',
    // MsgType: 'video',
    // MediaId: 'OMYnpghh8fRfzHL8obuboDN9rmLig4s0xdpoNT6a5BoFZWufbE6srbCKc_bxduzS',
    // ThumbMediaId: 'media_id',
    // MsgId: '5837397520665436492' }
}).shortvideo(function (message, req, res, next) {
    storage.putMessage(message);
    handle2('shortvideo', message, req, res);
    // message为短视频内容
    // { ToUserName: 'gh_d3e07d51b513',
    // FromUserName: 'oPKu7jgOibOA-De4u8J2RuNKpZRw',
    // CreateTime: '1359125022',
    // MsgType: 'shortvideo',
    // MediaId: 'OMYnpghh8fRfzHL8obuboDN9rmLig4s0xdpoNT6a5BoFZWufbE6srbCKc_bxduzS',
    // ThumbMediaId: 'media_id',
    // MsgId: '5837397520665436492' }
}).location(function (message, req, res, next) {
    storage.putMessage(message);
    handle2('location', message, req, res);
    // message为位置内容
    // { ToUserName: 'gh_d3e07d51b513',
    // FromUserName: 'oPKu7jgOibOA-De4u8J2RuNKpZRw',
    // CreateTime: '1359125311',
    // MsgType: 'location',
    // Location_X: '30.283950',
    // Location_Y: '120.063139',
    // Scale: '15',
    // Label: {},
    // MsgId: '5837398761910985062' }
}).link(function (message, req, res, next) {
    storage.putMessage(message);
    handle2('link', message, req, res);
    // message为链接内容
    // { ToUserName: 'gh_d3e07d51b513',
    // FromUserName: 'oPKu7jgOibOA-De4u8J2RuNKpZRw',
    // CreateTime: '1359125022',
    // MsgType: 'link',
    // Title: '公众平台官网链接',
    // Description: '公众平台官网链接',
    // Url: 'http://1024.com/',
    // MsgId: '5837397520665436492' }
}).event(function (message, req, res, next) {
    storage.putMessage(message);
    res.wait('view');
    // message为事件内容
    // { ToUserName: 'gh_d3e07d51b513',
    // FromUserName: 'oPKu7jgOibOA-De4u8J2RuNKpZRw',
    // CreateTime: '1359125022',
    // MsgType: 'event',
    // Event: 'LOCATION',
    // Latitude: '23.137466',
    // Longitude: '113.352425',
    // Precision: '119.385040',
    // MsgId: '5837397520665436492' }
}).device_text(function (message, req, res, next) {
    storage.putMessage(message);
    handle2('device_text', message, req, res);
    // message为设备文本消息内容
    // { ToUserName: 'gh_d3e07d51b513',
    // FromUserName: 'oPKu7jgOibOA-De4u8J2RuNKpZRw',
    // CreateTime: '1359125022',
    // MsgType: 'device_text',
    // DeviceType: 'gh_d3e07d51b513'
    // DeviceID: 'dev1234abcd',
    // Content: 'd2hvc3lvdXJkYWRkeQ==',
    // SessionID: '9394',
    // MsgId: '5837397520665436492',
    // OpenID: 'oPKu7jgOibOA-De4u8J2RuNKpZRw' }
}).device_event(function (message, req, res, next) {
    storage.putMessage(message);
    handle2('device_event', message, req, res);
    // message为设备事件内容
    // { ToUserName: 'gh_d3e07d51b513',
    // FromUserName: 'oPKu7jgOibOA-De4u8J2RuNKpZRw',
    // CreateTime: '1359125022',
    // MsgType: 'device_event',
    // Event: 'bind'
    // DeviceType: 'gh_d3e07d51b513'
    // DeviceID: 'dev1234abcd',
    // OpType : 0, //Event为subscribe_status/unsubscribe_status时存在
    // Content: 'd2hvc3lvdXJkYWRkeQ==', //Event不为subscribe_status/unsubscribe_status时存在
    // SessionID: '9394',
    // MsgId: '5837397520665436492',
    // OpenID: 'oPKu7jgOibOA-De4u8J2RuNKpZRw' }
})));

app.listen(18080, function () {
    console.log('Ready');
});